import JSZip from 'jszip';
import { saveAs } from 'file-saver';
export const addPanelsButton = (editor) => {
    let { Panels } = editor;
    // 删除原本的blocks按钮
    Panels.removeButton("views", "open-blocks");
    Panels.removeButton("options", "fullscreen");
    Panels.removeButton("options", "export-template");
    Panels.addButton("options", {
        id: "fullscreen",
        context: 'fullscreen',
        className: "",
        label: `<svg t="1720776585096" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="12581" data-spm-anchor-id="a313x.search_index.0.i8.55e73a81TStjmr" style="margin-bottom:-3px" width="16" height="16"><path d="M896 1024h-768A128 128 0 0 1 0 896v-768A128 128 0 0 1 128 0h768A128 128 0 0 1 1024 128v768a128 128 0 0 1-128 128z m64-896a64.028444 64.028444 0 0 0-64-64h-768A64.028444 64.028444 0 0 0 64 128v768a64.028444 64.028444 0 0 0 64 64h768a64.028444 64.028444 0 0 0 64-64z m-96.028444 352.028444a31.971556 31.971556 0 0 1-31.971556-32.028444l0.967111-210.488889-217.144889 217.201778-45.283555-45.226667 217.6-217.543111H576a32 32 0 1 1 0-64h287.061333a31.687111 31.687111 0 0 1 22.755556 9.614222 28.444444 28.444444 0 0 1 10.069333 22.357334v288.028444a31.971556 31.971556 0 0 1-32.028444 31.971556zM448 896H160.938667a31.857778 31.857778 0 0 1-22.755556-9.671111 28.444444 28.444444 0 0 1-10.069333-22.300445V576a32 32 0 1 1 64 0l-0.967111 210.488889 217.144889-217.201778 45.283555 45.283556-217.6 217.543111h212.138667a32 32 0 0 1 0 64z" p-id="12582"></path></svg>`,
        command: {
            run: function (editor) {
                editor.runCommand('fullscreen', { target: '.editorOutline' })
            },
            stop: function (editor) {
                editor.stopCommand('fullscreen', { target: '.editorOutline' })
            }
        },
        attributes: { title: '全屏' },
        active: false,
    })
    Panels.addButton("options", {
        id: "export-template",
        context: 'exportTemplate',
        className: "fa fa-code",
        command: "export-template",
        attributes: { title: '查看代码' },
        active: false,
    })
    // 添加撤销、回滚撤销和重做按钮
    Panels.addButton("options", {
        id: 'back',
        context: 'back',
        className: "fa fa-mail-reply",
        command: {
            run: function (editor) {
                editor.Commands.run('core:undo');
            },
        },
        attributes: { title: '撤销' },
        active: false,
    });
    // 输出编辑器自带命令
    console.log(editor.Commands.getAll());
    Panels.addButton("options", {
        id: 'forward',
        context: 'forward',
        className: "fa fa-mail-forward",
        command: {
            run: function (editor) {
                editor.Commands.run('core:redo');
            },
        },
        attributes: { title: '前滚' },
        active: false,
    });
    Panels.addButton("options", {
        id: 'clear',
        context: 'clear',
        className: "fa fa-trash-o",
        command: {
            run: function (editor) {
                var r = confirm("是否确认清空布局？");
                if (r == true) {
                    editor.Commands.run('core:canvas-clear');
                }
            },
        },
        attributes: { title: '清空' },
        active: false,
    });
    // 添加切换拖拽方式按钮
    Panels.addButton("options", {
        id: 'drag mode',
        context: 'dragMode',
        className: "fa fa-arrows",
        command: {
            run: function (editor) {
                // 设置可随意拖动，方便自定义位置
                editor.setDragMode("translate");
            },
            stop: function (editor) {
                // 恢复默认拖拽方式
                editor.setDragMode("");
            },
        },
        attributes: { title: '切换拖拽方式' },
        active: false,
    });
    // 添加导入文件(html)功能按钮
    let codeViewer = editor && editor.CodeManager.getViewer('CodeMirror').clone();
    let container = document.createElement("div");
    let btnImp = document.createElement("button");
    let bottomDiv = document.createElement("div");
    let innerDiv = document.createElement("div");
    let bottomText = document.createElement("span");
    bottomText.style = 'color:white;font-size:13px';
    bottomText.innerText = '请将html代码粘贴至文本区中';
    bottomDiv.appendChild(bottomText);
    bottomDiv.appendChild(innerDiv);
    bottomDiv.style = 'display:flex;align-items: center;justify-content: space-between;';
    innerDiv.style = 'width:230px;margin-top:5px;height:35px;display:flex;justify-content: space-between;';
    // 按钮样式
    //下拉菜单超链接样式
    const toStyle = 'font-size:13px;border-top: 0.5px solid lightgray;border-bottom:0.5px soild lightgray;cursor: pointer;transition: 0.5s;color: black;padding: 12px 16px;text-decoration: none;display: block;';
    //按钮外层样式
    const drop = 'position: relative;display: inline-block;';
    // 下拉菜单div样式
    const content = 'display: none;position: absolute;background-color: #f9f9f9;min-width: 110px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1;';
    // 下拉图标样式
    const icon = 'margin-left: 5px;';
    // 按钮样式
    const real = 'width:105px;height:35px;cursor: pointer;border:none;color:white;\
    text-align:center;background-color:#75c4e8fc;border-radius: 10px;'

    // 添加导入按钮
    let dropin = document.createElement("div");
    let dropinText = document.createElement("span");
    let dropinIcon = document.createElement("span");
    let dropinContent = document.createElement("div");
    let fileImport = document.createElement("a");//文件导入
    let pathImport = document.createElement("a");//地址导入
    // 动态创建文件选择元素  
    let fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.html,.zip';
    fileInput.style.display = 'none';
    dropin.style = drop;
    dropinContent.style = content;
    fileImport.style = toStyle;
    pathImport.style = toStyle;
    dropinIcon.style = icon;
    btnImp.style = real;
    dropinText.innerText = '导入模板';
    dropinIcon.innerText = '▼';
    fileImport.innerText = '文件导入';
    pathImport.innerHTML = '路径导入';

    // 导入事件
    btnImp.onclick = () => {
        let code = codeViewer.editor.getValue();
        editor.DomComponents.getWrapper().set('content', '');
        editor.setComponents(code);
        editor.Modal.close();
    };
    codeViewer.set({
        codeName: 'htmlmixed',
        readOnly: 0
    });

    // 导入下拉列表触发事件
    const importClick = () => {
        fileInput.click();//选择文件
        dropinContent.style.display = "none";
        dropinIcon.textContent = "▼";
    }
    // 文件导入事件
    fileImport.onclick = importClick;
    pathImport.onclick = () => {
        // 远端导入
        let path = prompt("请输入远端文件路径", 'http://localhost:8081/html/switch.html');
        if (path === '') return;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', path, true);
        xhr.setRequestHeader('Accept', 'text/html');
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 处理接收到的HTML数据  
                codeViewer.setContent(xhr.responseText || '');
            }
        };
        xhr.send();
    };

    // 文件选择监听
    // zip包解析函数
    const parseZip = async (file) => {
        const zip = await JSZip.loadAsync(file);
        let promises = [];

        // 遍历所有文件，为每个文件创建一个 promise，解析出.html文件和.css文件
        Object.keys(zip.files).forEach(filename => {
            const fileInZip = zip.files[filename];

            if (fileInZip.name.endsWith('.html')) {
                promises.push(fileInZip.async('text').then(content => ({ type: 'html', content })));
            } else if (fileInZip.name.endsWith('.css')) {
                promises.push(fileInZip.async('text').then(content => ({ type: 'css', content })));
            }
        });

        // 等待所有 promise 解决  
        const results = await Promise.all(promises);

        // 初始化 html 和 css 变量  
        let html = '';
        let css = '';

        // 处理结果  
        results.forEach(result => {
            if (result.type === 'html') {
                // 如果存在多个.html 文件，仅取第一个
                html = result.content; // 这里我假设我们只关心第一个 .html 文件  
            } else if (result.type === 'css') {
                css += result.content; // 累加所有 .css 文件的内容  
            }
        });

        return { html, css };
    };
    // 为input元素添加change事件监听器  
    fileInput.onchange = (event) => {
        var file = event.target.files[0];
        if (file) {
            // 判断文件类型 
            if (file.type === 'text/html') {
                var reader = new FileReader();
                reader.onload = function (e) {
                    codeViewer.setContent(e.target.result || '');
                };
                reader.readAsText(file); // 以文本形式读取文件
            } else if (file.type === 'application/x-zip-compressed') {
                // 解析zip包
                parseZip(file).then(({ html, css }) => {
                    let result = '';
                    // 删除head标签内容
                    let doc = new DOMParser().parseFromString(html, "text/html");
                    doc.head.parentNode.removeChild(doc.head);
                    html = doc.documentElement.outerHTML;
                    if (html.endsWith('</html>')) {
                        // 替换</html>为<style>...</style></html>  
                        result = `
                        ${html.slice(0, -7)} 
                            <style> 
                                ${css} 
                            </style>
                        </html>`;
                    } else {
                        result = `${html}
                        <style>
                            ${css}
                        </style>`;
                    }
                    codeViewer.setContent(result || '');
                })
            } else { alert('选择的文件格式错误！'); }
            fileInput.value = '';//置空
        }
    };

    // 点击导入按钮右侧下拉图标
    dropinIcon.onclick = (event) => {
        event.stopPropagation(); // 阻止事件冒泡  
        var dropinIcon = event.target;
        if (dropinContent.style.display === "block") {
            dropinContent.style.display = "none";
            dropinIcon.textContent = "▼";
        } else {
            dropinContent.style.display = "block";
            dropinIcon.textContent = "▲";
        }
    };

    // 元素组合
    btnImp.appendChild(dropinText);
    btnImp.appendChild(dropinIcon);
    fileImport.appendChild(fileInput);
    dropinContent.appendChild(fileImport);
    dropinContent.appendChild(pathImport);
    dropin.appendChild(btnImp);
    dropin.appendChild(dropinContent);
    innerDiv.appendChild(dropin);

    // 在导入html模板界面添加导出zip按钮
    let dropdown = document.createElement("div");
    let exportbtn = document.createElement("button");//导出按钮
    let dropdownText = document.createElement("span");
    let dropdownIcon = document.createElement("span");
    let dropdownContent = document.createElement("div");
    let toZip = document.createElement("a");//导出分为html和css样式的zip
    let toHtml = document.createElement("a");
    // let toRemote = document.createElement("a");
    dropdown.style = drop;
    dropdownContent.style = content;
    toZip.style = toStyle;
    toHtml.style = toStyle;
    // toRemote.style = toStyle;
    dropdownIcon.style = icon;
    exportbtn.style = real;
    dropdownText.innerText = '导出zip包';
    dropdownIcon.innerText = '▼';
    toZip.innerText = '导出zip包';
    toZip.dataset.text = '导出zip包';
    toHtml.innerText = '导出html';
    toHtml.dataset.text = '导出html';
    // toRemote.innerText = '导出远端';
    // toRemote.dataset.text = '导出远端';

    // 点击导出按钮右侧下拉图标
    dropdownIcon.onclick = (event) => {
        event.stopPropagation(); // 阻止事件冒泡  
        var dropdownIcon = event.target;
        if (dropdownContent.style.display === "block") {
            dropdownContent.style.display = "none";
            dropdownIcon.textContent = "▼";
        } else {
            dropdownContent.style.display = "block";
            dropdownIcon.textContent = "▲";
        }
    };
    // 导出下拉菜单选中事件
    dropdownContent.onclick = (e) => {
        dropdownText.innerText = e.target.dataset.text;
        dropdownContent.style.display = "none";
        dropdownIcon.textContent = "▼";
    };
    // 添加点击事件监听器，点击下拉菜单以外的地方时收起下拉菜单  
    document.addEventListener('click', function (event) {
        if (!dropdown.contains(event.target)) {
            dropdownContent.style.display = "none";
            dropdownIcon.textContent = "▼";
        }
        if (!dropin.contains(event.target)) {
            dropinContent.style.display = "none";
            dropinIcon.textContent = "▼";
        }
    });
    exportbtn.onclick = async () => {
        var fileName = prompt("请输入文件名", "exported_project");
        // 判空
        if (fileName == null || fileName === "") return;
        let code = codeViewer.editor.getValue();
        editor.DomComponents.getWrapper().set('content', '');
        editor.setComponents(code);
        const zip = new JSZip();
        const htmlContent =
            `<!DOCTYPE html>
        <html>
            <head>
                <link rel="stylesheet" href="style.css">
            </head>
            ${editor.getHtml()}
        </html>`;
        const cssContent = editor.getCss();
        // const jsContent = editor.getJs();

        if (dropdownText.innerText === '导出zip包') {
            zip.file("index.html", htmlContent);
            zip.file("style.css", cssContent);
            // zip.file("script.js", jsContent);
        } else if (dropdownText.innerText === '导出html') {
            const tmpl =
                `<!DOCTYPE html>
            <html>
                <head></head>
                ${editor.getHtml()}
                <style>
                    ${cssContent}
                </style>
            </html>`;
            zip.file("index.html", tmpl);
        } else { editor.Modal.close(); return; }
        await zip.generateAsync({ type: 'blob' }).then((content) => {
            saveAs(content, `${fileName}.zip`);// 下载操作
            // 创建一个FormData对象，后端处理
            // const formData = new FormData();  
            // formData.append('file', content, 'example.zip')//MultipartFile file后端接收类型
            // console.log(content)
        });
        // 等待所有 promise 解决  
        // const results = await Promise.all(promises);
        editor.Modal.close();
    };
    // 元素组合
    exportbtn.appendChild(dropdownText);
    exportbtn.appendChild(dropdownIcon);
    dropdownContent.appendChild(toZip);
    dropdownContent.appendChild(toHtml);
    //   dropdownContent.appendChild(toRemote);
    dropdown.appendChild(exportbtn);
    dropdown.appendChild(dropdownContent);
    innerDiv.appendChild(dropdown);
    //   导入/导出功能按钮
    Panels.addButton("options", {
        id: 'openImport',
        className: "fa fa-download",
        command: {
            run: function (editor1) {
                let md = editor1.Modal;
                let modalContent = md.getContentEl();//导入html模板的文本区标签
                md.setTitle('导入/导出HTML模板');
                let viewer = codeViewer.editor;
                if (!viewer) {
                    let txtarea = document.createElement('textarea');
                    container.appendChild(txtarea);
                    container.appendChild(bottomDiv);
                    codeViewer.init(txtarea);
                    viewer = codeViewer.editor;
                }
                const strHtml = editor.html` $${editor.getHtml()}<style>$${'\n' + editor.getCss() + '\n'}</style>`;
                md.setContent('');
                md.setContent(container);
                codeViewer.setContent(strHtml || '');
                md.open();
                viewer.refresh();
            },
        },
        attributes: { title: '导入/导出html' },
        active: false,
    });
}